import React, { Component } from 'react';
import { Map } from 'react-amap';
import { Input } from 'antd';

class LocationSearch extends Component {
  componentDidMount() {
    const { __map__: map } = this.props;
    // 初始化显示中心点经纬度及定位组件
    const { lng, lat } = map.F.center;
    this.getLocation(lng, lat, map);
    // map绑定点击事件
    map.on('click', ({ lnglat }) => this.getLocation(lnglat.getLng(), lnglat.getLat(), map));

    window.AMap.plugin('AMap.Autocomplete', () => {
      // 实例化Autocomplete
      const autoOptions = {
        // input 为绑定输入提示功能的input的DOM ID
        input: 'tipinput',
      };
      const autoComplete = new window.AMap.Autocomplete(autoOptions);
      window.AMap.event.addListener(autoComplete, 'select', this.inputSelect); // 注册监听，当选中某条记录时会触发
    });
  }

  inputSelect = e => {
    const { __map__: map } = this.props;
    if (e.poi && e.poi.location) {
      map.setZoom(15);
      map.setCenter(e.poi.location);
      const { lng, lat } = e.poi.location;
      this.getLocation(lng, lat, map);
    } else {
      document.getElementById('lnglat').value = '';
    }
  };

  getLocation = (lng, lat, map) => {
    document.getElementById('lnglat').value = `${lng},${lat}`;
    // 清除旧标记
    if (window.marker) {
      window.marker.setMap(null);
      window.marker = null;
    }
    // 构造点标记
    window.marker = new window.AMap.Marker({
      icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
      position: [lng, lat],
    });
    window.marker.setMap(map);
  };

  render() {
    return (
      <div>
        关键字搜索：
        <Input id="tipinput" style={{ width: '5rem' }} />
        经纬度：
        <Input id="lnglat" readOnly style={{ width: '5rem' }} />
      </div>
    );
  }
}

const LocationMap = () => (
  <div style={{ width: '100%', height: '10rem' }}>
    <Map zoom={15} resizeEnable>
      <LocationSearch />
    </Map>
  </div>
);

export default LocationMap;
